package com.share.tools;

import lombok.extern.slf4j.Slf4j;
import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.net.ftp.FTPClientConfig;
import org.apache.commons.net.ftp.FTPReply;

import java.io.*;
import java.util.TimeZone;
import java.util.zip.ZipEntry;
import java.util.zip.ZipFile;
import java.util.zip.ZipInputStream;

/**
 * @author caifan
 * @date 2019/10/18
 */
@Slf4j
public class FTPUtils {
    /**
     * 连接ftp服务器
     * @param host
     * @param port
     * @param username
     * @param password
     * @return
     */
    public static FTPClient connectFTP(String host, Integer port, String username, String password){
        FTPClientConfig ftpClientConfig = null;
        log.info("create ftpClientConfig...");
        ftpClientConfig = new FTPClientConfig(FTPClientConfig.SYST_UNIX);
        ftpClientConfig.setServerTimeZoneId(TimeZone.getDefault().getID());
        ftpClientConfig.setServerLanguageCode("UTF-8");
        FTPClient ftpClient = new FTPClient();
        ftpClient.configure(ftpClientConfig);
        try {
            if (null != port){
                ftpClient.connect(host, port);
            }else {
                ftpClient.connect(host);
            }
            int reply = ftpClient.getReplyCode();
            if (!FTPReply.isPositiveCompletion(reply)){
                throw new RuntimeException("ftp server reply error");
            }
            ftpClient.login(username, password);
            //设置传输协议
            ftpClient.enterLocalPassiveMode();
            ftpClient.setFileType(FTPClient.BINARY_FILE_TYPE);
            log.info("login ftp success");
            ftpClient.setDataTimeout(30000);
        }catch (Exception e){
            log.error("登录服务器失败！", e.getMessage(), e);
        }
        return ftpClient;
    }

    /**
     * 退出登录并断开服务器连接
     * @param ftpClient
     */
    public static void disConnectFTP(FTPClient ftpClient){
        if (null != ftpClient && ftpClient.isConnected()){
            try {
                ftpClient.logout();
                log.info("success logout from ftp server");
            } catch (IOException e) {
                log.error("logout form ftp server error", e.getMessage(), e);
            } finally {
                try {
                    ftpClient.disconnect();
                } catch (IOException e) {
                    log.error("disconnect from ftp server error", e.getMessage(), e);
                }
            }
        }
    }
    /**
     * 读取压缩文件
     * @param localPath
     * @return
     */
    public static String zipToString(String localPath){
        StringBuilder stringBuilder = new StringBuilder();
        ZipEntry zipEntry = null;
        ZipFile zipFile = null;
        ZipInputStream inputStream = null;
        try {
            zipFile = new ZipFile(localPath);
            File file = new File(localPath);
            inputStream = new ZipInputStream(new FileInputStream(file));
            while ((zipEntry = inputStream.getNextEntry()) != null){
                //如果是文件
                if (!zipEntry.isDirectory()) {
                    log.info("zipEntry name {}", zipEntry.getName());
                    BufferedReader reader = new BufferedReader(
                            new InputStreamReader(zipFile.getInputStream(zipEntry)));
                    String str = null;
                    while ((str = reader.readLine()) != null) {
                        log.info("str {}", str);
                        stringBuilder.append(str).append("\\n");
                    }
                    reader.close();
                }
            }
            //删除压缩文件
            file.delete();
        } catch (IOException e) {
            log.error("UnZip error", e.getMessage(), e);
        } finally {
            try {
                //关闭当前打开的项
                inputStream.closeEntry();
                zipFile.close();
                inputStream.close();
            }catch (IOException e){
                log.error("close object error", e.getMessage(), e);
            }
        }
        return stringBuilder.toString();
    }
}
